﻿using System;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Litografia.BusinessComponents;
using Litografia.BusinessEntities;
using Nortec.Security;

namespace Litografia.UI.Mantenimientos
{
    public partial class MantGastosForm : BaseForm
    {
        #region Constructors

        public MantGastosForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Declarations

        private BEGasto.GastoRow selectedRow;
        private BEGasto.GastoDataTable gastos;

        #endregion

        #region Event Handlers

        private void MantGastosForm_Load(object sender, EventArgs e)
        {
            ConfigureToolBar(toolStrip, ToolBarButtons.Save |
                                        ToolBarButtons.New |
                                        ToolBarButtons.Delete |
                                        ToolBarButtons.Close);
            LoadList(true);
            ConfigureGrid();
            toolStrip.ItemClicked += toolStrip_ItemClicked;
            ToggleButton(toolStrip, ToolBarButtons.Delete, false);
        }

        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch ((ToolBarButtons)e.ClickedItem.Tag)
            {
                case ToolBarButtons.Save:
                    Save();
                    break;
                case ToolBarButtons.Delete:
                    Delete();
                    break;
                case ToolBarButtons.New:
                    ClearControls(Controls);
                    conceptoTextBox.Focus();
                    grid.Selected.Rows.Clear();
                    grid.Refresh();
                    break;
                case ToolBarButtons.Close:
                    Close();
                    break;
            }
        }

        private void grid_Click(object sender, EventArgs e)
        {
            //grid.Selected.Rows 
        }

        private void grid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            if (grid.Selected.Rows.Count > 0)
            {
                if (grid.Selected.Rows[0].IsDataRow)
                {
                    var selectedId = (int)grid.Selected.Rows[0].Cells[gastos.IdColumn.Ordinal].Value;
                    selectedRow = gastos.FindById(selectedId);
                    UnPack(selectedRow);
                    ToggleButton(toolStrip, ToolBarButtons.Delete, true);
                }
                else grid.Selected.Rows.Clear();
            }
            else
            {
                selectedRow = null;
                ClearControls(Controls);
                ToggleButton(toolStrip, ToolBarButtons.Delete, false);
            }
        }

        #endregion

        #region Methods: Non-Public

        private void Delete()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (selectedRow == null)
                    MessageBox.Show("Debe seleccionar un registro antes de eliminarlo.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                else
                {
                    if (MessageBox.Show("¿Está seguro de eliminar el registro \"" + selectedRow.Concepto + "\"?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        BCGasto.Delete(selectedRow.Id);
                        ClearControls(Controls);
                        LoadList(false);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayError("No se pudo eliminar la información.", ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void Save()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (ValidateEntries())
                {
                    var row = Pack();
                    if (selectedRow == null)
                        BCGasto.Add(row);
                    else
                        BCGasto.Update(row);
                    ClearControls(Controls);
                    LoadList(false);
                }
            }
            catch (Exception ex)
            {
                DisplayError("No se pudo guardar la información.", ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private bool ValidateEntries()
        {
            var functionReturnValue = false;
            var msg = "";
            decimal monto;

            if (string.IsNullOrEmpty(conceptoTextBox.Text))
            {
                msg = "Debe ingresar el concepto";
                conceptoTextBox.Focus();
            }
            else if (!Decimal.TryParse(montoTextBox.Text, out monto) || monto <= 0)
            {
                msg = "El monto no es válido";
                montoTextBox.Focus();
            }
            else
                functionReturnValue = true;

            if (!functionReturnValue)
                MessageBox.Show(msg, Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            return functionReturnValue;
        }

        private BEGasto.GastoRow Pack()
        {
            var gasto = (new BEGasto.GastoDataTable()).NewGastoRow();

            if (selectedRow != null)
                gasto.Id = selectedRow.Id;
            gasto.EmpresaId = NortecMembership.CompanyId;
            gasto.Concepto = conceptoTextBox.Text.Trim();
            gasto.Monto = Convert.ToDecimal(montoTextBox.Text);
            gasto.Tipo = directoRadioButton.Checked ? "D" : "I";

            return gasto;
        }

        private void UnPack(BEGasto.GastoRow row)
        {
            conceptoTextBox.Text = row.Concepto;
            montoTextBox.Text = row.Monto.ToString();
            if (row.Tipo == "D")
                directoRadioButton.Checked = true;
            else
                indirectoRadioButton.Checked = true;
        }

        private void LoadList(bool sort)
        {
            gastos = BCGasto.Get();
            grid.DataSource = gastos;

            if (sort)
            {
                grid.DisplayLayout.Bands[0].SortedColumns.Clear();
                grid.DisplayLayout.Bands[0].SortedColumns.Add(grid.DisplayLayout.Bands[0].Columns[gastos.ConceptoColumn.Ordinal], false);
            }

            if (grid.Rows.Count > 0)
            {
                grid.ActiveRow = grid.Rows[0];
            }
            else
            {
                selectedRow = null;
                ToggleButton(toolStrip, ToolBarButtons.Delete, false);
            }
        }

        private void ConfigureGrid()
        {
            // Oculta algunas columnas 
            grid.DisplayLayout.Bands[0].Columns[gastos.EmpresaIdColumn.Ordinal].Hidden = true;
            grid.DisplayLayout.Bands[0].Columns[gastos.IdColumn.Ordinal].Hidden = true;
            grid.DisplayLayout.Bands[0].Columns[gastos.TipoColumn.Ordinal].Hidden = true;

            // Alineamientos
            foreach (var col in grid.DisplayLayout.Bands[0].Columns)
                col.Header.Appearance.TextHAlign = HAlign.Center;
            grid.DisplayLayout.Bands[0].Columns[gastos.MontoColumn.Ordinal].CellAppearance.TextHAlign = HAlign.Right;

            // Ancho de columnas
            grid.DisplayLayout.Bands[0].Columns[gastos.ConceptoColumn.Ordinal].Width = 300;
            grid.DisplayLayout.Bands[0].Columns[gastos.TipoNombreColumn.Ordinal].Width = 100;
            grid.DisplayLayout.Bands[0].Columns[gastos.MontoColumn.Ordinal].Width = 100;

            // Formato de despliege
            grid.DisplayLayout.Bands[0].Columns[gastos.MontoColumn.Ordinal].Format = "#,##0.00";

            // Filters
            grid.DisplayLayout.Bands[0].Columns[gastos.ConceptoColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.True;
            grid.DisplayLayout.Bands[0].Columns[gastos.MontoColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.True;
            grid.DisplayLayout.Bands[0].Columns[gastos.TipoNombreColumn.Ordinal].AllowRowFiltering = DefaultableBoolean.True;
            grid.DisplayLayout.Bands[0].Override.CellClickAction = CellClickAction.RowSelect;

            grid.DisplayLayout.GroupByBox.Prompt = GridGroupBoxText;
        }

        #endregion

    }
}
